<script setup>
import * as API from '@/api/store/log-product-number.js'
import * as APIProduct from "@/api/store/product.js"
import * as APIStore from "@/api/store/store.js"
import {onMounted, ref, reactive} from "vue";
import {getLocalTime} from "@/utils/time.js";
import "@/views/store/inventory/index.vue";
import {ElMessage} from "element-plus";

// 用于搜索框
const productNameList = ref([])
const productNameMap = ref({})
const searchOption = reactive({
  productId: null,
})
// 用于表格
const storeNameList = ref([])
const storeNameMap = ref({})
const inventoryRecordList = ref([])
const pn = ref(1)
const ps = ref(10)
const total = ref(0)
const typeList = ref([
  {label: '入库', value: 0},
  {label: '出库', value: 1},
])

// 用于对话框
const dialogFormVisible = ref(false)

let inventoryRecordParams = reactive({
  id: null,
  productId: null,
  type: null,
  logTime: null,
  number: null,
  notes: null,
})


const getPage = async (pager = 1)=>{
  pn.value = pager
  const result = await API.reqPage(
      pn.value,
      ps.value,
      searchOption.productId
  )
  if (result.code === '0') {
    total.value = result.data.total
    // inventoryRecordList.value = []
    // result.data.items.forEach(item => {
    //   inventoryRecordList.value.push(item)
    // })
    inventoryRecordList.value = result.data.items
  }
}

const addInventory = ()=>{
  dialogFormVisible.value = true
  Object.assign(inventoryRecordParams, {
    id: null,
    productId: null,
    type: null,
    logTime: null,
    number: null,
    notes: null,
  })
}

const updateInventory = (row)=>{
  dialogFormVisible.value = true
  Object.assign(inventoryRecordParams, row)
}

const deleteInventory = async (id)=>{
  const result = await API.reqDelete(id)
  if (result.code === '0') {
    ElMessage({ type: 'success', message: '删除成功' })
    await getPage(inventoryRecordList.value.length > 1 ? pn.value : pn.value - 1);
  }
}

const search = async ()=>{
  await getPage()
}

const cancel = ()=>{
  dialogFormVisible.value = false
}

const confirm = async ()=>{
  let result
  if(inventoryRecordParams.id){
    result = await API.reqUpdate(inventoryRecordParams)
  }else{
    result = await API.reqSave(inventoryRecordParams)
  }
  if (result.code === '0') {
    ElMessage({ type: 'success', message: inventoryRecordParams.id? '修改成功':'添加成功',})
    dialogFormVisible.value = false
    await getPage()
  } else {
    dialogFormVisible.value = false
    //提示消息
    ElMessage({ type: 'error', message: inventoryRecordParams.id ? '修改失败' : '添加失败' });
  }
}

const getStoreNameList = async ()=>{
  await APIStore.reqStoreNameList().then(resp => {
    storeNameList.value = resp.data.items.map(x => {
      return { label: x.name, value: x.id }
    })
    // 使用普通对象作为映射表
    storeNameMap.value = resp.data.items.reduce((map, x) => {
      map[x.id] = x.name;
      return map;
    }, {});
  })
}

onMounted(() => {
  APIProduct.reqNameList().then(resp => {
    productNameList.value = resp.data.items.map(x => {
      return { label: x.name, value: x.id }
    })
  })
  getStoreNameList()
  getPage()
})
</script>
<script>
export default {
  name: "Inventory"
}
</script>
<template>
  <!-- ----------------------------------- search ----------------------------------- -->
  <el-card>
    <el-scrollbar always>
      <el-form class="search-card">
        <div class="search-input">
          <el-form-item label="货品名">
            <el-select v-model="searchOption.productId" clearable placeholder="货品名" style="width:180px">
              <el-option
                  v-for="item in productNameList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" size="default" @click="search" >搜索</el-button>
        </el-form-item>
      </el-form>
    </el-scrollbar>
  </el-card>
  <!-- ----------------------------------- search ----------------------------------- -->

  <!-- ----------------------------------- table ----------------------------------- -->
  <el-card>
    <el-button type="primary" size="default" @click="addInventory">添加货品记录</el-button>

    <el-table style="margin: 10px 0;" border :data="inventoryRecordList">
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column label="货品名" align="center" prop="productName" show-overflow-tooltip></el-table-column>
      <el-table-column label="分店" align="center" prop="storeId" show-overflow-tooltip>
        <template #="{row}">
          <span>{{ storeNameMap[row.storeId] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="type" show-overflow-tooltip>
        <template #="{row}">
          <p>{{ typeList[row.type].label }}</p>
        </template>
      </el-table-column>
      <el-table-column label="时间" align="center" prop="logTime" show-overflow-tooltip>
        <template #="{ row }">
          <span>{{getLocalTime(row.logTime, 1)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="number" show-overflow-tooltip></el-table-column>
      <el-table-column label="备注" align="center" prop="notes" show-overflow-tooltip></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip>
        <template #="{row}">
          <span>{{getLocalTime(row.createTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" show-overflow-tooltip>
        <template #="{ row }">
          <span>{{ getLocalTime(row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px" align="center">
        <template #="{ row }">
          <el-row>
            <el-col :span="12">
              <el-button type="primary" size="small" icon="Edit" @click="updateInventory(row)">编辑</el-button>
            </el-col>
            <el-col :span="12">
              <el-popconfirm :title="`确定要删除?`" width="260px" @confirm="deleteInventory(row.id)">
                <template #reference>
                  <el-button type="primary" size="small" icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="getPage()"
        @current-change="getPage"
        v-model:current-page="pn"
        v-model:page-size="ps"
        :page-sizes="[10, 20, 50, 100]"
        :background="true"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
    />
  </el-card>
  <!-- ----------------------------------- table ----------------------------------- -->

  <!-- ----------------------------------- dialog ----------------------------------- -->
  <el-dialog
      v-model="dialogFormVisible"
      :title="inventoryRecordParams.id? '修改货品记录' : '添加货品记录'"
  >
    <el-form style="width: 80%" :model="inventoryRecordParams">
      <el-form-item label="货品名" label-width="100px">
        <el-select v-model="inventoryRecordParams.productId" clearable placeholder="货品名" style="width:180px">
          <el-option
              v-for="item in productNameList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" label-width="100px">
        <el-select v-model="inventoryRecordParams.type" clearable placeholder="类型" style="width:180px">
          <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间" label-width="100px">
        <el-date-picker
            v-model="inventoryRecordParams.logTime"
            type="date"
            placeholder="时间"
            size="small"
        />
      </el-form-item>
      <el-form-item label="数量" label-width="100px">
        <el-input v-model="inventoryRecordParams.number"></el-input>
      </el-form-item>
      <el-form-item label="备注" label-width="100px">
        <el-input v-model="inventoryRecordParams.notes" type="textarea"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
      <el-button type="primary" size="default" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
  <!-- ----------------------------------- dialog ----------------------------------- -->
</template>

<style scoped lang="css">
.search-card {
  display: flex;
  align-items: center;
  flex-direction: row;
}
.search-input {
  display: flex;
  align-items: center;
  flex: 1 0 auto;
}
.search-input > * {
  flex: 0 1 auto;
  margin-right: 2rem;
}
.search-card .el-form-item {
  margin-bottom: 0;
}
.el-card {
  margin-bottom: 2rem;
}
</style>